
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.AutoMapper;
using Abp.Linq.Extensions;
using Abp.Extensions;
using Abp.Domain.Repositories;
using L._52ABP.Common.Extensions.Enums;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using LTMCompanyName.YoyoCmsTemplate.Exam;
using LTMCompanyName.YoyoCmsTemplate.Exam.Dtos;
using LTMCompanyName.YoyoCmsTemplate.Exam.Exporting;
using LTMCompanyName.YoyoCmsTemplate.Exam.DomainService;
using LTMCompanyName.YoyoCmsTemplate.Authorization;
using LTMCompanyName.YoyoCmsTemplate.Dtos;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Text;

namespace LTMCompanyName.YoyoCmsTemplate.Exam
{
    /// <summary>
    /// 应用层服务的接口实现方法
	/// <see cref="StockSubmit" />
    ///</summary>
    public class StockSubmitAppService : YoyoCmsTemplateAppServiceBase, IStockSubmitAppService
    {


        private readonly IStockSubmitListExcelExporter _stockSubmitListExcelExporter;

        private readonly IRepository<StockSubmit, long> _stockSubmitRepository;

        private readonly IStockSubmitManager _stockSubmitManager;

        private readonly IRepository<StockCategory, long> _stockCategoryRepository;

        /// <summary>
        /// 构造函数
        ///</summary>

        public StockSubmitAppService(StockSubmitListExcelExporter stockSubmitListExcelExporter, IRepository<StockSubmit, long> stockSubmitRepository, IStockSubmitManager stockSubmitManager, IRepository<StockCategory, long> stockCategoryRepository)
        {
            _stockSubmitListExcelExporter = stockSubmitListExcelExporter;
            this._stockSubmitRepository = stockSubmitRepository;
            this._stockSubmitManager = stockSubmitManager;
            this._stockCategoryRepository = stockCategoryRepository;
        }


        /// <summary>
        /// 获取的分页列表信息
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(StockSubmitPermissions.StockSubmit_Query)]
        public async Task<PagedResultDto<StockSubmitListDto>> GetPaged(GetStockSubmitsInput input)
        {
            var query = this._stockSubmitRepository.GetAll().AsNoTracking().WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.StockName.Contains(input.FilterText));
            // TODO:根据传入的参数添加过滤条件 .Where(a=>a.CreatorUserId== AbpSession.UserId)

            var count = await query.CountAsync();

            var stockSubmitList = await query
            .OrderBy(input.Sorting).AsNoTracking()
            .PageBy(input)
            .ToListAsync();

            // 包装列表需要显示的字段
            var stockSubmitListDtos = stockSubmitList.Select(item =>
            {
                return new StockSubmitListDto
                {
                    Id = item.Id,
                    InsertTime = item.CreationTime.ToString("G"),
                    StockId = item.StockId,
                    StudentName = item.StudentName,
                    ClassName = item.ClassName,
                    CategoryName = this._stockCategoryRepository.Get(item.StockId)?.Name,
                    StudentId = item.StudentId,
                    TotalScore = item.TotalScore,
                    StockScore = item.StockScore,
                    QuestionCount = item.QuestionCount,
                    AnswerRightCount = item.AnswerRightCount,
                    UseTime = item.UseTime,
                };
            }).ToList();

            return new PagedResultDto<StockSubmitListDto>(count, stockSubmitListDtos);
        }


        /// <summary>
        /// 通过指定id获取StockSubmitListDto信息
        /// </summary>
        [AbpAuthorize(StockSubmitPermissions.StockSubmit_Query)]
        public async Task<StockSubmitListDto> GetById(EntityDto<long> input)
        {
            var entity = await _stockSubmitRepository.GetAsync(input.Id);

            var dto = ObjectMapper.Map<StockSubmitListDto>(entity);
            return dto;
        }

        /// <summary>
        /// 获取编辑 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<GetStockSubmitForEditOutput> GetForEdit(NullableIdDto<long> input)
        {
            var output = new GetStockSubmitForEditOutput();
            StockSubmitEditDto editDto;

            if (input.Id.HasValue)
            {


                var entity = await _stockSubmitRepository.GetAsync(input.Id.Value);
                editDto = ObjectMapper.Map<StockSubmitEditDto>(entity);
            }
            else
            {
                editDto = new StockSubmitEditDto();
            }



            output.StockSubmit = editDto;
            return output;
        }


        /// <summary>
        /// 添加或者修改的公共方法
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task CreateOrUpdate(CreateOrUpdateStockSubmitInput input)
        {

            if (input.StockSubmit.Id.HasValue)
            {
                await Update(input.StockSubmit);
            }
            else
            {
                await Create(input.StockSubmit);
            }
        }


        /// <summary>
        /// 新增
        /// </summary>
        protected virtual async Task<StockSubmitEditDto> Create(StockSubmitEditDto input)
        {
            //TODO:新增前的逻辑判断，是否允许新增

            var entity = ObjectMapper.Map<StockSubmit>(input);
            //调用领域服务
            entity = await _stockSubmitRepository.InsertAsync(entity);

            var dto = ObjectMapper.Map<StockSubmitEditDto>(entity);
            return dto;
        }

        /// <summary>
        /// 编辑
        /// </summary>
        protected virtual async Task Update(StockSubmitEditDto input)
        {
            //TODO:更新前的逻辑判断，是否允许更新

            var entity = await _stockSubmitRepository.GetAsync(input.Id.Value);
            //  input.MapTo(entity);
            //将input属性的值赋值到entity中
            ObjectMapper.Map(input, entity);
            await _stockSubmitRepository.UpdateAsync(entity);
        }



        /// <summary>
        /// 删除信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(StockSubmitPermissions.StockSubmit_Delete)]
        public async Task Delete(EntityDto<long> input)
        {
            //TODO:删除前的逻辑判断，是否允许删除
            await _stockSubmitRepository.DeleteAsync(input.Id);
        }



        /// <summary>
        /// 批量删除StockSubmit的方法
        /// </summary>
        [AbpAuthorize(StockSubmitPermissions.StockSubmit_BatchDelete)]
        public async Task BatchDelete(List<long> input)
        {
            // TODO:批量删除前的逻辑判断，是否允许删除
            await this._stockSubmitRepository.DeleteAsync(a => input.Contains(a.Id));
        }




        /// <summary>
        /// 导出为excel文件
        /// </summary>
        /// <returns></returns>
        [AbpAuthorize(StockSubmitPermissions.StockSubmit_ExportExcel)]
        public async Task<FileDto> GetToExcelFile()
        {
            var stockSubmits = await this._stockSubmitRepository.GetAll().ToListAsync();
            var stockSubmitListDtos = ObjectMapper.Map<List<StockSubmitListDto>>(stockSubmits);
            return _stockSubmitListExcelExporter.ExportToExcelFile(stockSubmitListDtos,this._stockCategoryRepository);
        }



        //// custom codes



        //// custom codes end

    }
}


